package com.wx.lock.zooKeeper;

import java.util.concurrent.*;

/**
 * @author wx
 * @Description: 分布式锁测试
 * @date 2018/11/30 003011:29
 */
public class DistributedLockTest {
    private static final int threadNum = 10;
    private static final CountDownLatch latch = new CountDownLatch(threadNum);

    public static void main(String[] agrs) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 200, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(5));
        for (int i = 0; i < threadNum; i++) {
            final int code = i;
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    //创建锁
                    DistributedLock distributedLock = new DistributedLock(new DoTemplate() {
                        @Override
                        public void dodo() {
                            System.out.println("执行分布式业务-编号" + code);
                        }
                    });
                    //获取锁
                    boolean lock = distributedLock.getLock();
                    if (lock) {
                        distributedLock.run();
                        distributedLock.unLock();
                    }
                    latch.countDown();
                }

            });

        }
        try {
            latch.await();
            System.out.println("所有线程执行完毕");
            executor.shutdown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
